package com.aps.service.excel;

import com.baomidou.mybatisplus.annotation.TableName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Excel导入策略接口
 */
public interface ExcelImportStrategy {
    
    /**
     * 获取实体类
     */
    Class<?> getEntityClass();
    
    /**
     * 获取列配置
     */
    List<ExcelColumnConfig> getColumnConfigs();
    
    /**
     * 业务规则验证
     */
    List<ExcelValidationError> validateBusinessRules(Map<String, Object> rowData, Integer rowIndex);
    
    /**
     * 保存实体数据
     */
    int saveEntities(List<Object> entities);
    
    /**
     * 预处理数据（可选）
     */
    default void preprocessData(Map<String, Object> rowData) {
        // 默认不做处理
    }
    
    /**
     * 后处理数据（可选）
     */
    default void postprocessData(List<Object> entities) {
        // 默认不做处理
    }
}

/**
 * 工单导入策略
 */
@Component
public class WorkOrderImportStrategy implements ExcelImportStrategy {
    
    @Autowired
    private WorkOrderService workOrderService; // 假设有这个服务
    
    @Override
    public Class<?> getEntityClass() {
        return WorkOrder.class;
    }
    
    @Override
    public List<ExcelColumnConfig> getColumnConfigs() {
        return List.of(
            new ExcelColumnConfig("workOrderId", "工单编号", "W-001", true, String.class),
            new ExcelColumnConfig("orderId", "订单编号", "O-1001", true, String.class),
            new ExcelColumnConfig("productId", "产品编号", "P-3001", true, String.class),
            new ExcelColumnConfig("deliveryDate", "交付日", "2023-12-31", true, java.time.LocalDate.class),
            new ExcelColumnConfig("quantity", "数量", "100", true, Integer.class),
            new ExcelColumnConfig("priority", "优先级", "高", true, String.class)
        );
    }
    
    @Override
    public List<ExcelValidationError> validateBusinessRules(Map<String, Object> rowData, Integer rowIndex) {
        List<ExcelValidationError> errors = new java.util.ArrayList<>();
        
        // 工单编号唯一性验证
        String workOrderId = (String) rowData.get("workOrderId");
        if (workOrderId != null && workOrderService.existsByWorkOrderId(workOrderId)) {
            errors.add(new ExcelValidationError(rowIndex, "workOrderId", workOrderId, "工单编号已存在"));
        }
        
        // 产品编号有效性验证
        String productId = (String) rowData.get("productId");
        if (productId != null && !isValidProductId(productId)) {
            errors.add(new ExcelValidationError(rowIndex, "productId", productId, "产品编号不存在"));
        }
        
        // 数量合理性验证
        Object quantity = rowData.get("quantity");
        if (quantity != null) {
            try {
                int qty = Integer.parseInt(quantity.toString());
                if (qty <= 0 || qty > 10000) {
                    errors.add(new ExcelValidationError(rowIndex, "quantity", quantity, "数量应在1-10000之间"));
                }
            } catch (NumberFormatException e) {
                errors.add(new ExcelValidationError(rowIndex, "quantity", quantity, "数量格式错误"));
            }
        }
        
        return errors;
    }
    
    @Override
    public int saveEntities(List<Object> entities) {
        List<WorkOrder> workOrders = (List<WorkOrder>) entities;
        return workOrderService.saveBatch(workOrders);
    }
    
    @Override
    public void preprocessData(Map<String, Object> rowData) {
        // 预处理：标准化优先级值
        String priority = (String) rowData.get("priority");
        if (priority != null) {
            priority = priority.trim();
            if ("1".equals(priority) || "高优先级".equals(priority)) {
                rowData.put("priority", "高");
            } else if ("2".equals(priority) || "中优先级".equals(priority)) {
                rowData.put("priority", "中");
            } else if ("3".equals(priority) || "低优先级".equals(priority)) {
                rowData.put("priority", "低");
            }
        }
    }
    
    private boolean isValidProductId(String productId) {
        // 实际实现中应该查询产品数据库
        return productId.startsWith("P-");
    }
}

/**
 * 设备导入策略
 */
@Component
public class DeviceImportStrategy implements ExcelImportStrategy {
    
    @Autowired
    private DeviceService deviceService; // 假设有这个服务
    
    @Override
    public Class<?> getEntityClass() {
        return Device.class;
    }
    
    @Override
    public List<ExcelColumnConfig> getColumnConfigs() {
        return List.of(
            new ExcelColumnConfig("deviceId", "设备编号", "DEV-001", true, String.class),
            new ExcelColumnConfig("deviceName", "设备名称", "加工中心1号", true, String.class),
            new ExcelColumnConfig("deviceType", "设备类型", "CNC", true, String.class),
            new ExcelColumnConfig("capacity", "产能", "100", true, Integer.class),
            new ExcelColumnConfig("status", "状态", "正常", true, String.class)
        );
    }
    
    @Override
    public List<ExcelValidationError> validateBusinessRules(Map<String, Object> rowData, Integer rowIndex) {
        List<ExcelValidationError> errors = new java.util.ArrayList<>();
        
        // 设备编号唯一性验证
        String deviceId = (String) rowData.get("deviceId");
        if (deviceId != null && deviceService.existsByDeviceId(deviceId)) {
            errors.add(new ExcelValidationError(rowIndex, "deviceId", deviceId, "设备编号已存在"));
        }
        
        // 设备类型验证
        String deviceType = (String) rowData.get("deviceType");
        if (deviceType != null && !isValidDeviceType(deviceType)) {
            errors.add(new ExcelValidationError(rowIndex, "deviceType", deviceType, "设备类型不支持"));
        }
        
        return errors;
    }
    
    @Override
    public int saveEntities(List<Object> entities) {
        List<Device> devices = (List<Device>) entities;
        return deviceService.saveBatch(devices);
    }
    
    private boolean isValidDeviceType(String deviceType) {
        return List.of("CNC", "冲压", "焊接", "装配", "包装").contains(deviceType);
    }
}

/**
 * 工单实体（示例）
 */
@TableName("work_order")
class WorkOrder {
    @ExcelColumn(value = "工单编号", required = true)
    private String workOrderId;
    
    @ExcelColumn(value = "订单编号", required = true)
    private String orderId;
    
    @ExcelColumn(value = "产品编号", required = true)
    private String productId;
    
    @ExcelColumn(value = "交付日", required = true, format = "date")
    private java.time.LocalDate deliveryDate;
    
    @ExcelColumn(value = "数量", required = true, format = "range:1,10000")
    private Integer quantity;
    
    @ExcelColumn(value = "优先级", required = true, format = "enum:高,中,低")
    private String priority;
    
    // 构造函数、getter、setter省略
    public WorkOrder() {}
    
    // getters and setters
    public String getWorkOrderId() { return workOrderId; }
    public void setWorkOrderId(String workOrderId) { this.workOrderId = workOrderId; }
    
    public String getOrderId() { return orderId; }
    public void setOrderId(String orderId) { this.orderId = orderId; }
    
    public String getProductId() { return productId; }
    public void setProductId(String productId) { this.productId = productId; }
    
    public java.time.LocalDate getDeliveryDate() { return deliveryDate; }
    public void setDeliveryDate(java.time.LocalDate deliveryDate) { this.deliveryDate = deliveryDate; }
    
    public Integer getQuantity() { return quantity; }
    public void setQuantity(Integer quantity) { this.quantity = quantity; }
    
    public String getPriority() { return priority; }
    public void setPriority(String priority) { this.priority = priority; }
}

/**
 * 设备实体（示例）
 */
@TableName("device")
class Device {
    @ExcelColumn(value = "设备编号", required = true)
    private String deviceId;
    
    @ExcelColumn(value = "设备名称", required = true)
    private String deviceName;
    
    @ExcelColumn(value = "设备类型", required = true)
    private String deviceType;
    
    @ExcelColumn(value = "产能", required = true, format = "range:1,1000")
    private Integer capacity;
    
    @ExcelColumn(value = "状态", required = true, format = "enum:正常,维修,停用")
    private String status;
    
    // 构造函数、getter、setter省略
    public Device() {}
    
    // getters and setters (省略具体实现)
}

/**
 * 服务接口（示例）
 */
interface WorkOrderService {
    boolean existsByWorkOrderId(String workOrderId);
    int saveBatch(List<WorkOrder> workOrders);
}

interface DeviceService {
    boolean existsByDeviceId(String deviceId);
    int saveBatch(List<Device> devices);
}
